<template>
    <div>
        <el-form :model="updateRole" ref="roleFormRef" label-width="100px" label-position="right" style="width: 400px;"
            :rules="rules">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="updateRole.name" aria-placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-tree style="max-width: 600px" :data="authList" show-checkbox node-key="index" :default-expand-all="true"
                :default-checked-keys="checkedKeys" @check-change="handleCheckChange" />
        </el-form>
    </div>
</template>
<script setup lang="ts">
import type { roleInfoData } from '@/api/role/type';
import type { FormRules } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
// 引入菜单项对象数组
import menuList from '@/config/menuConfig';
// 接收父组件传递过来要编辑的角色对象
const props = defineProps(['role'])
let updateRole = ref<roleInfoData>({
    name: ''
})
// 表单校验规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
});
// 树形控件数据数组
const authList = ref([])
// 树形控件所选中的元素
const checkedKeys = ref<string[]>([])
// 处理树形控件元素对象
const getAuthNodes = (menuList:any)=>{
    return menuList.map((item:any)=>{
        if(!item.children){
            return{
                index:item.index,
                label:item.title
            }
        }else{
            return{
                index:item.index,
                label:item.title ,
                children:getAuthNodes(item.children)
            }
        }
    })
}
interface Tree {
  index: string
}
// 树形控件选择回调
const handleCheckChange = (
    data: Tree,
    checked: boolean,
    indeterminate: boolean
) => {
    console.log(data, checked, indeterminate)
    
    // 如果选中就添加到选项中数组中
    if(checked){
        if(checkedKeys.value.indexOf(data.index) == -1){
            checkedKeys.value.push(data.index)
        }
    }else{
        if(checkedKeys.value.indexOf(data.index) != -1){
            checkedKeys.value.splice(checkedKeys.value.indexOf(data.index),1)
        }
    }
    console.log(updateRole.value.menus);
    console.log(checkedKeys.value);
    
}
// 为父组件提供数据方法
const getMenus = ()=>{
    updateRole.value.menus = checkedKeys.value
    return updateRole.value
}
// 对外暴露
defineExpose({
    getMenus
})
onMounted(() => {
    updateRole.value = { ...props.role }
    // Object.assign(updateRole, props.role);
    authList.value = getAuthNodes(menuList)
    checkedKeys.value = [...props.role.menus]
})
</script>

<style scoped></style>